package cn.wk.service.impl;

import cn.wk.AjaxResult;
import cn.wk.StrUtils;
import cn.wk.ValidUtils;
import cn.wk.client.MovieFeign;
import cn.wk.domain.MoveticketBuy;
import cn.wk.domain.Movie;
import cn.wk.dto.BuyTicketDto;
import cn.wk.dto.MovieDto;
import cn.wk.exception.GlobalException;
import cn.wk.mapper.MoveticketBuyMapper;
import cn.wk.service.IMoveticketBuyService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import javafx.scene.shape.MoveTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wk
 * @since 2021-03-18
 */
@Service
public class MoveticketBuyServiceImpl extends ServiceImpl<MoveticketBuyMapper, MoveticketBuy> implements IMoveticketBuyService {
    @Autowired
    private MovieFeign movieFeign;

    /**
     * 购票服务提供电影票购买接口，用户可以通过该接口购买电影票，同时保存购票记录
     * @param buyTicketDto
     * @return
     */
    @Override
    public String buyTicked(BuyTicketDto buyTicketDto) {
        //对数据进行判断
        Long moveId = buyTicketDto.getMoveId();
        Integer number = buyTicketDto.getNumber();
        Integer userId = buyTicketDto.getUserId();
        ValidUtils.assertNotNull(moveId,"请选择要购买的电影");
        ValidUtils.assertNotNull(number,"请选择购买数量");
        ValidUtils.assertNotNull(userId,"用户参数错误，请重试");
        //这里先购票，需要用feign去调用
        Movie movie = new Movie();
        movie.setId(moveId);
        AjaxResult ajaxResult = movieFeign.goBuy(movie);
        if(!ajaxResult.isSuccess()){
            throw new GlobalException("该电影异常，请重新选购");
        }
        //从那边返回该电影票的详细信息
        String dbMovie = (String)ajaxResult.getResultObj();
        Movie movieJson = JSON.parseObject(dbMovie, Movie.class);
        if(buyTicketDto.getNumber() > movieJson.getTicketNumber()){
            throw new GlobalException("票数超过了可购买的限制");
        }
        //获取该电影的单价
        BigDecimal price = movieJson.getPrice();
        //获取总价
        BigDecimal totalPrice = price.multiply(new BigDecimal(Integer.parseInt(buyTicketDto.getNumber().toString())));
        //保存数据
        MoveticketBuy moveticketBuy = new MoveticketBuy();
        moveticketBuy.setMovieId(buyTicketDto.getMoveId());
        moveticketBuy.setNumber(buyTicketDto.getNumber());
        moveticketBuy.setPayAmount(totalPrice);
        moveticketBuy.setUserId(buyTicketDto.getUserId());
        //生成一个取票码 4 位长度
        String ticketCode = StrUtils.getRandomString(4);
        moveticketBuy.setTicketCode(ticketCode);
        baseMapper.insert(moveticketBuy);
        //更新票数
        MovieDto movieDto = new MovieDto(buyTicketDto.getMoveId(), buyTicketDto.getNumber());
        movieFeign.updateTicked(movieDto);
        //返回取票码
        return ticketCode;
    }
}
